package cc.yaomm.service.basic.mapper.user;

import cc.yaomm.common.basic.base.SuperMapper;
import cc.yaomm.service.basic.entity.user.UsersPermissionsRef;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Mapper
public interface UsersPermissionsRefMapper extends SuperMapper<UsersPermissionsRef> {

    /**
     * 根据角色ID查询关联权限
     *
     * @param roleIds
     * @return
     */
    default Set<Long> findPermissionsByRoleId(Collection<Long> roleIds) {
        LambdaQueryWrapper<UsersPermissionsRef> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(UsersPermissionsRef::getPermissionId);
        wrapper.eq(UsersPermissionsRef::getUserId, 0L);
        wrapper.in(UsersPermissionsRef::getRoleId, roleIds);
        return this.selectList(wrapper).stream().map(UsersPermissionsRef::getPermissionId).collect(Collectors.toSet());
    }

    /**
     * 根据权限ID查询关联资源
     *
     * @param permissionIds
     * @return
     */
    default Set<String> findResourcesByPermissionId(Collection<Long> permissionIds) {
        LambdaQueryWrapper<UsersPermissionsRef> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(UsersPermissionsRef::getResourceCode);
        wrapper.eq(UsersPermissionsRef::getRoleId, 0L);
        wrapper.in(UsersPermissionsRef::getPermissionId, permissionIds);
        return this.selectList(wrapper).stream().map(UsersPermissionsRef::getResourceCode).collect(Collectors.toSet());
    }

    /**
     * 删除权限关联的资源数据
     *
     * @param permissionId
     */
    @Delete("DELETE FROM users_permissions_ref WHERE role_id = 0 AND permission_id = #{permissionId}")
    void deleteResource(@Param("permissionId") Long permissionId);

    /**
     * 删除角色关联的权限数据
     *
     * @param roleId
     */
    @Delete("DELETE FROM users_permissions_ref WHERE user_id = 0 AND role_id = #{roleId}")
    void deletePermission(@Param("roleId") Long roleId);

}
